package com.github.willisaway.core.util;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.Data;

/**
 * 计时工具类，主要用来调试性能时计时
 * @author liyougen
 *
 */
public class TimerUtil {
    private static Logger logger = LoggerFactory.getLogger(TimerUtil.class);
    
    private List<Snapshot> snapshots=new ArrayList<Snapshot>();
    
    public TimerUtil() {
        snap("开始");
    }
    public void snap(String desc) {
        Date time = new Date();
        Snapshot snapshot = new Snapshot();
        snapshot.setDesc(desc);
        snapshot.setTime(time);
        snapshots.add(snapshot);
        logger.warn(desc);
    }
    
    public void print() {
        Snapshot firstsnapshot = snapshots.get(0);
        Snapshot lastsnapshot = null;
        for(int i=0;i<snapshots.size();i++) {
            Snapshot snapshot = snapshots.get(i);
            //logger.warn("时间监控:desc："+snapshot.getDesc()+",当前时间是:"+DateUtil.format(snapshot.getTime(),"HH:mm:ss"));
            if(i>0) {
                logger.warn("时间监控:desc:"+snapshot.getDesc()+"用时毫秒数:"+(snapshot.getTime().getTime()-lastsnapshot.getTime().getTime())+",总用时："+(snapshot.getTime().getTime()-firstsnapshot.getTime().getTime()));
            }
            lastsnapshot = snapshot;
        }
    }
    
    @Data
    public class Snapshot{
        String desc;
        Date time;
    }
    
    public static void main(String[]args) throws Exception{
        TimerUtil util = new TimerUtil();
        util.snap("第1次");
        Thread.sleep(1000);
        util.snap("第2次");
        Thread.sleep(2000);
        util.snap("第3次");
        util.print();
    }
}
